package com.operator.Activitys.activity;

import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.operator.Activitys.R;
import com.operator.Activitys.activity.base.BaseActivity;
import com.operator.Activitys.bean.MoneyState;
import com.operator.Activitys.bean.State;
import com.operator.Activitys.bean.User;
import com.operator.Activitys.dialog.PopEnterPassword;
import com.operator.Activitys.http.manager.UserManager;
import com.operator.Activitys.utils.Constant;
import com.operator.Activitys.utils.JumperUtils;
import com.operator.Activitys.utils.ToastUtils;
import com.operator.Activitys.utils.UiUtil;
import com.zhy.autolayout.AutoRelativeLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：金泽云 手机app
 * 类描述：提现
 * 创建人：张飞祥
 * 创建时间：2018/5/23 16:17
 * 修改人：张飞祥
 * 修改时间：2018/5/23 16:17
 * 修改备注：
 */
public class PutForwardActivity extends BaseActivity implements TextWatcher {

    //返回按钮
    @Bind(R.id.iv_return)
    ImageView ivReturn;
    //标题
    @Bind(R.id.tv_title)
    TextView tvTitle;
    //功能键
    @Bind(R.id.tv_function)
    TextView tvFunction;
    //标题总布局
    @Bind(R.id.app_bar_layout)
    AutoRelativeLayout appBarLayout;
    //提现金额
    @Bind(R.id.et_put_forward_number)
    EditText etPutForwardNumber;
    //余额
    @Bind(R.id.tv_put_forward_money)
    TextView tvPutForwardMoney;
    //温馨提示
    @Bind(R.id.tv_prompt)
    TextView tvPrompt;

    //提现金额
    private double mPutForwardMoney;
    //初始化网络请求
    public UserManager mApiManager;
    //TODO 当前 内存中 用户信息
    private User mACacheUser = null;
    //提现输入金额
    private double mAmount = 0;
    //现有金额
    private double mRemainder = 0;

    //支付 弹窗
    private PopEnterPassword mPopPayPwd = null;

    //获取内存中提现提示信息
    private String mPrompt = "";

    @Override
    protected void initUI() {
        setContentView(R.layout.act_put_forward);
        //网络请求接口 常驻方法
        mApiManager = mApiManager.getUserApiManager(this, this.getTaskId());
        //TODO 获取内存用户实体
        Gson gson = new Gson();
        mACacheUser = gson.fromJson(mACache.getAsJSONObject(Constant.CACHE_USER) + "", User.class);
        //TODO 获取内存中 提现提示信息
        mPrompt = mACache.getAsString(Constant.CACHE_LOGIN_PUT_FORWARD_MSG);

        //设置标题
        tvTitle.setText("提现");
        //显示返回按钮
        ivReturn.setVisibility(View.VISIBLE);
        //显示功能按钮
        tvFunction.setVisibility(View.VISIBLE);
        //显示功能按钮 文字
        tvFunction.setText("提现记录");
        //设置状态栏 背景颜色
        appBarLayout.setBackgroundResource(R.color.color_bg_blue);
        //设置提现信息
        tvPrompt.setText(mPrompt);
    }

    @Override
    protected void initData() {
        //提现其他数量 文字输入监听 事件
        etPutForwardNumber.addTextChangedListener(this);
        //显示金额
        tvPutForwardMoney.setText("当前余额：" + mACacheUser.getRemainder() + "元");
    }

    /**
     * 金额其他数量监听事件
     */
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        //TODO 获取内存 最新的 用户实体
        User user = new Gson().fromJson(mACache.getAsJSONObject(Constant.CACHE_USER) + "", User.class);

        //TODO 判断当前 显示的具体价格
        if (charSequence.toString().equals(".")) {
            //清空数据源
            etPutForwardNumber.setText("");
        }else if (!charSequence.toString().equals("")){
            //设置现有金额
            mRemainder =user.getRemainder();
            //提现数量
            mAmount = Double.parseDouble(charSequence.toString());
            //逻辑判断
            if (mAmount > mRemainder) {
                etPutForwardNumber.setText(mRemainder + "");
                //设置 提现金额
                mPutForwardMoney = mRemainder;
                return;
            } else {
                //设置 提现金额
                mPutForwardMoney = mAmount;
            }
        }else {
            //初始化 提现金额
            mPutForwardMoney = 0;
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }


    /**
     * 极光推送 更新余额信息
     *
     * @param JPushMoney
     */
    @Subscriber(tag = Constant.BUS_MY_REMAINDER)
    public void onJpushShopMoneyPush(double JPushMoney) {
        //TODO 更新 页面上的 店铺实体
        mACacheUser.setRemainder(JPushMoney);
        //更新显示金额
        tvPutForwardMoney.setText("当前余额：" + JPushMoney + "元");
    }

    /**
     * 按钮点击事件
     */
    @OnClick({R.id.iv_return, R.id.tv_function, R.id.btn_put_forward})
    public void onBtnClick(View v) {
        switch (v.getId()) {

            case R.id.iv_return:            //返回
                finish();
                break;

            case R.id.tv_function:          //提现记录
                JumperUtils.JumpTo(this, PutForwardListActivity.class);
                break;

            case R.id.btn_put_forward:      //提现

                //TODO 隐藏其他数量 软件盘
                UiUtil.hideKeyboard(etPutForwardNumber, PutForwardActivity.this);
                //TODO 开始业务逻辑判断
                if (mPutForwardMoney == 0) {
                    ToastUtils.showShort(PutForwardActivity.this, "请输入提现金额！");
                } else if (mPutForwardMoney < 100) {
                    ToastUtils.showShort(PutForwardActivity.this, "提现金额不能小于100！");
                } else if ((mPutForwardMoney % 10) != 0) {
                    ToastUtils.showShort(PutForwardActivity.this, "提现金额必须是10的倍数！");
                } else {
                    /**
                     * 重新 获取用户实体对象，判断 支付密钥是否为空
                     * true： 跳转 设置 支付密码
                     * false：则直接 开启支付
                     */
                    mACacheUser = new Gson().fromJson(mACache.getAsJSONObject(Constant.CACHE_USER) + "", User.class);
                    if (mACacheUser.getTsPwd() != null  && !mACacheUser.getTsPwd().equals("")){
                        //弹出支付软件盘
                        setShowPayPopupView("提现", mPutForwardMoney);
                    }else{
                        JumperUtils.JumpTo(this,PayManageActivity.class);
                    }
                }
                break;
        }
    }

    /**
     * 显示 支付视图弹窗
     */
    private void setShowPayPopupView(String title, double money) {

        //TODO 配置弹窗
        mPopPayPwd = new PopEnterPassword(PutForwardActivity.this, title, money) {
            //输入支付密码完成后，所要进行的操作
            @Override
            public void setOnFinishInput(String pwd) {
                //弹出加载框
                initShowTimeDialog("正在验证支付密钥....", PutForwardActivity.this);
                //开始验证支付密码
                mApiManager.userCheckPayPwd(mACacheUser.getId(), pwd);
            }
        };

        /**
         * 显示 支付窗口
         * ps：设置 “Gravity” layout在PopupWindow中显示的位置
         */
        mPopPayPwd.showAtLocation(PutForwardActivity.this.findViewById(R.id.layout_put_forward),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 验证支付 报错
     */
    @Subscriber(tag = Constant.BUS_MY_CHECK_PAY_ERROR, mode = ThreadMode.MAIN)
    public void initCheckPayError(String strError) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //销毁加载提示框
                timeDialog.dismiss();
                //弹出提示
                ToastUtils.showShort(PutForwardActivity.this, "提现失败，网络连接不稳定！");
            }
        }, 2000);
    }

    /**
     * 验证支付
     */
    @Subscriber(tag = Constant.BUS_MY_CHECK_PAY, mode = ThreadMode.MAIN)
    public void initCheckPay(final State state) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //TODO 判断当前是否验证成功
                if (state.getState().equals("1")) {
                    //设置 支付标题
                    timeDialog.setContent("正在提现，请稍候...");
                    //开始网络请求
                    mApiManager.userPutForward(mACacheUser.getId(), mPutForwardMoney);
                } else {
                    //销毁加载提示框
                    timeDialog.dismiss();
                    //显示提示信息 dialog
                    new MaterialDialog.Builder(PutForwardActivity.this)
                            .content("支付密码错误，请重试")
                            .negativeText("重试")
                            .negativeColor(Color.parseColor("#cccccc"))
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    //弹出支付软件盘
                                    setShowPayPopupView("提现", mPutForwardMoney);
                                }
                            })
                            .positiveText("忘记密码")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    //跳转忘记 支付密码页面
                                    JumperUtils.JumpTo(PutForwardActivity.this, PayForgetPwdActivity.class);
                                }
                            }).show();
                }
            }
        }, 2000);
    }

    /**
     * 提现 报错
     */
    @Subscriber(tag = Constant.BUS_MY_PUT_FORWARD_ERROR, mode = ThreadMode.MAIN)
    public void initPutForwardError(String httpPutForwardError) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏加载
                timeDialog.dismiss();
                //弹出提示
                ToastUtils.showShort(PutForwardActivity.this, "提现失败，网络连接不稳定！");
            }
        }, 2000);
    }

    /**
     * 提现 返回数据
     */
    @Subscriber(tag = Constant.BUS_MY_PUT_FORWARD, mode = ThreadMode.MAIN)
    public void initPutForward(final MoneyState state) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏加载
                timeDialog.dismiss();
                //TODO 业务逻辑判断
                if ("1".equals(state.getState())) {

                    //保存新的 用户余额参数
                    mACacheUser.setRemainder(state.getCurentRemainder());
                    mACache.put(Constant.CACHE_USER, new Gson().toJson(mACacheUser));
                    //清空输入文本
                    etPutForwardNumber.setText("");
                    //更新显示金额
                    tvPutForwardMoney.setText("当前余额：" + state.getCurentRemainder() + "元");
                    //更新我的页面 余额
                    EventBus.getDefault().post(state.getCurentRemainder(), Constant.BUS_MY_REMAINDER);
                }
                //弹出提示
                ToastUtils.showShort(PutForwardActivity.this, state.getMsg());
            }
        }, 2000);
    }
}
